<?php

/* echo "<pre>";
  print_r($_POST);
  echo "</pre>"; 
 */
//SANITIZE ALL ESCAPES
$sanitize_all_escapes = true;
//
//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;

$ignoreAuth = true;

require_once("../../globals.php");
require_once("$srcdir/forms.inc");
require_once("$srcdir/sql.inc");
require_once("$srcdir/encounter.inc");
require_once("$srcdir/acl.inc");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/formdata.inc.php");
require_once ("$srcdir/patient_provider.inc.php");

$conn = $GLOBALS['adodb']['db'];

$date_tmp = str_replace('/', '-',  formData('form_date', 'P'));
$date= date('Y-m-d', strtotime($date_tmp));
$onset_date = formData('form_onset_date', 'P');
$sensitivity = formData('form_sensitivity', 'P');
$pc_catid = formData('pc_catid', 'P');
$facility_id = formData('facility_id', 'P');
$billing_facility = formData('billing_facility', 'P');
$reason = formData('reason', 'P');
$mode = formData('mode', 'P');
$referral_source = formData('form_referral_source', 'P');
//$consul_fexa = formData('consul_fexa', 'P');
//$consul_plan = formData('consul_plan', 'P');
//$consul_sick = formData('consul_sick', 'P');
$pc_condid = formData('pc_condid', 'P');
$pc_typid = formData('pc_typid', 'P');
$pc_causaid = formData('pc_causaid', 'P');
$pc_conductid = formData('pc_conductid', 'P');


$myquery = "SELECT * FROM patient_data pd inner join patient_facility pf on (pd.pid = pf.pid) WHERE pd.pid = $pid";
$res = sqlStatement($myquery);
$row = sqlFetchArray($res);
$facility_id = $row['facility_id'];

$facilityresult = sqlQuery("select name FROM facility WHERE id = $facility_id");
$facility = $facilityresult['name'];

$existePacienteMedico = -1;
if ($mode == 'new') {
    $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
    
    $query = "INSERT INTO form_encounter SET " .
                    "date = '$date', " .
                    "onset_date = '$onset_date', " .
                    "reason = '$reason', " .
                    "facility = '" . add_escape_custom($facility) . "', " .
                    "pc_catid = '$pc_catid', " .
                    "facility_id = '$facility_id', " .
                    "billing_facility = '$billing_facility', " .
                    "sensitivity = '$sensitivity', " .
                    "referral_source = '$referral_source', " .
                    "pid = '$pid', " .
                    /*"encounter = '$encounter', " .*/
                    "provider_id = '$provider_id', ".
                    //"consul_fexa= '$consul_fexa', ".
                    //"consul_plan= '$consul_plan', ".
                    "consul_sick= '$consul_sick', ".
                    //"pc_condid= '$pc_condid', ".
					"pc_causaid = '$pc_causaid', " .
                    "pc_conductid = '$pc_conductid', " .
                    
                    "pc_typid = '$pc_typid' ";
    //echo $query;
    off_sync($query);
    //echo $query;
    $encounter = sqlInsert($query);

    $query2 = "UPDATE form_encounter SET encounter = '$encounter' WHERE id='$encounter'";
    
    sqlStatement($query2);
    
    off_sync($query2);
    addForm($encounter, "New Patient Encounter",$encounter, "newpatient", $pid, $userauthorized, $date);

    
    $existePacienteMedico = existePacienteMedico($provider_id, $pid);
    if ($existePacienteMedico == 0) {
        crearRelacionPacienteMedico($provider_id, $pid);
    }
    crearRelacionPacienteMedicoVisita($encounter);
    
} else if ($mode == 'update') {
    $id = $_POST["id"];
    $result = sqlQuery("SELECT encounter, sensitivity FROM form_encounter WHERE id = '$id'");
    if ($result['sensitivity'] && !acl_check('sensitivities', $result['sensitivity'])) {
        die("You are not authorized to see this encounter.");
    }
    $encounter = $result['encounter'];
    // See view.php to allow or disallow updates of the encounter date.
    $datepart = acl_check('encounters', 'date_a') ? "date = '$date', " : "";
    
    $query = "UPDATE form_encounter SET " .
            $datepart .
            "onset_date = '$onset_date', " .
            "reason = '$reason', " .
            "facility = '$facility', " .
            "pc_catid = '$pc_catid', " .
            "facility_id = '$facility_id', " .
            "billing_facility = '$billing_facility', " .
            "sensitivity = '$sensitivity', " .
            "referral_source = '$referral_source', " .
            "consul_fexa= '$consul_fexa', ".
            "consul_plan= '$consul_plan', ".
            "consul_sick= '$consul_sick', ".
            "pc_condid= '$pc_condid', ".
            "pc_typid = '$pc_typid' ".
            "WHERE id = '$id'";
    sqlStatement($query);
    //Insert into bitacora
    off_sync($query);
} else {
    die("Unknown mode '$mode'");
}

setencounter($encounter);

// Update the list of issues associated with this encounter.
$query = "DELETE FROM issue_encounter WHERE " .
        "pid = '$pid' AND encounter = '$encounter'";
sqlStatement($query);

//Insert into bitacora
off_sync($query);
if (is_array($_POST['issues'])) {
    foreach ($_POST['issues'] as $issue) {
        $query = "INSERT INTO issue_encounter ( " .
                "pid, list_id, encounter " .
                ") VALUES ( " .
                "'$pid', '$issue', '$encounter'" .
                ")";
        sqlStatement($query);
        //Insert into bitacora
        off_sync($query);
    }
}

$result4 = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
        " left join openemr_postcalendar_categories on fe.pc_catid=openemr_postcalendar_categories.pc_catid  WHERE fe.pid = '$pid' order by fe.date desc");

echo "patient_file/encounter/forms.php?set_encounter=" . $encounter . "&patiente_existe=" . $existePacienteMedico;
?>